<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\MessageBag;

class AuthenticationController extends Controller
{
  public function __construct(Request $request)
  {
    parent::__construct($request);
  }

  public function showLoginForm()
  {
    Log::info(__METHOD__);

    $locales = $data = [];
    $errors = null;
    $localesUrl = $this->coreApiEndpoint . '/locales?limit=3';
    $response = Http::get($localesUrl);

    if (200 == $response->status()) {
      $data = json_decode($response, true);
      $locales = $data['data'];
    }
    else {
      $errors = new MessageBag(
        ['message' => $response->json()['message']]
      );
    }

    return view('authentication.login', ['locales' => $locales, 'fullLocale' => $this->fullLocale]);
  }

  public function login(Request $request)
  {
    Log::info(__METHOD__);

    $email = $request->input('email');
    $password = $request->input('password');
    $locale = $request->input('locale');
    $fullLocale = substr($locale, 0, 5);
    $loginUrl = $this->coreApiEndpoint . '/login';
    $data = $userData = $roleData = $user = $userRole = $userPermissions = [];
    $response = $userResponse = $roleResponse = $errors = null;
    $userUrl = $roleUrl = $userPicture = '';
    $enableAccounts = $enableGeographicals = $enableLookups = $enableSystem = false;

    $response = Http::post($loginUrl, [
      'email' => $email,
      'password' => $password,
      'locale' => $fullLocale
    ]);
    if (200 == $response->status()) {
      $data = json_decode($response, true);
      $request->session()->put('locale', substr($locale, 0, 2));
      $request->session()->put('fullLocale', $fullLocale);
      $request->session()->put('coreapi_token', $data['coreapi_token']);
      $userUrl = $this->coreApiEndpoint . '/authenticatedUser';
      $userResponse = Http::withHeaders([
        'Authorization' => 'Bearer ' . $data['coreapi_token'],
      ])->get($userUrl);
      $user = json_decode($userResponse, true)['user'];
      $userUrl = $this->coreApiEndpoint . '/users/' . $user['id'] . '?include[]=role&include[]=picture';
      $userResponse = Http::withHeaders([
        'Authorization' => 'Bearer ' . $data['coreapi_token'],
      ])->get($userUrl);
      $userData = json_decode($userResponse, true);
      $userRole = $userData['resource']['role'];
      if ($userData['resource']['picture']) {
        $userPicture =  $userData['resource']['picture']['filename'];
        $userPicture = $this->coreApiPublicEndpoint . substr($userPicture, (strpos($userPicture, '/public/') + 7));
      }
      $roleUrl = $this->coreApiEndpoint . '/roles/' . $userRole['id'] . '?include=permissions';
      $roleResponse = Http::withHeaders([
        'Authorization' => 'Bearer ' . $data['coreapi_token'],
      ])->get($roleUrl);
      $roleData = json_decode($roleResponse, true);
      $userPermissions = $roleData['resource']['permissions'];
      $request->session()->put('user', $user);
      if ($userData['resource']['picture']) {
        $request->session()->put('user_picture', $userPicture);
      }
      $request->session()->put('user_role', $userRole);
      $request->session()->put('user_permissions', $userPermissions);

      // accounts menu
      if (
        (false !== array_search('read-users', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-roles', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-permissions', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-people', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-companies', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-addresses', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-telephones', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-emails', array_column($userPermissions, 'slug')))
      ) {
        $enableAccounts = true;
      } else {
        $enableAccounts = false;
      }
      $request->session()->put('enable_accounts', $enableAccounts);
      // geographicals menu
      if (
        (false !== array_search('read-countries', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-regions', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-districts', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-cities', array_column($userPermissions, 'slug')))
        || (false !== array_search('read-zipcodes', array_column($userPermissions, 'slug')))
      ) {
        $enableGeographicals = true;
      } else {
        $enableGeographicals = false;
      }
      $request->session()->put('enable_geographicals', $enableGeographicals);
      // lookups menu
      if (
        false !== array_search('read-types', array_column($userPermissions, 'slug'))
      ) {
        $enableLookups = true;
      } else {
        $enableLookups = false;
      }
      $request->session()->put('enable_lookups', $enableLookups);
      // system menu
      if (
        false !== array_search('read-languages', array_column($userPermissions, 'slug'))
        || false !== array_search('read-locales', array_column($userPermissions, 'slug'))
      ) {
        $enableSystem = true;
      } else {
        $enableSystem = false;
      }
      $request->session()->put('enable_system', $enableSystem);

      $request->session()->save();

      return redirect('/')->with('success', $data['message']);
    }

    if (422 == $response->status()) {
      $errors = new MessageBag($response->json());
    }
    else {
      $errors = new MessageBag(
        ['message' => $response->json()['message']]
      );
    }

    return back()
      ->withErrors($errors)
      ->withInput();
  }

  public function logout(Request $request)
  {
    Log::info(__METHOD__);

    $locale = request()->query('locale');
    $logoutUrl = $this->coreApiEndpoint . '/logout?locale=' . $locale;
    $response = null;

    $response = Http::withHeaders([
      'Authorization' => 'Bearer ' . $request->session()->get('coreapi_token'),
    ])->get($logoutUrl);

    $request->session()->put('enable_system', false);
    $request->session()->put('enable_lookups', false);
    $request->session()->put('enable_geographicals', false);
    $request->session()->put('enable_accounts', false);
    $request->session()->pull('user_permissions');
    $request->session()->pull('user_role');
    if ($request->session()->get('user_picture')) {
      $request->session()->pull('user_picture');
    }
    $request->session()->pull('user');
    $request->session()->pull('coreapi_token');
    $request->session()->pull('fullLocale');
    $request->session()->pull('locale');

    $request->session()->save();

    return redirect('/')->with('success', $response->json()['message']);
  }
}
